<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 16/8/10
 * Time: 上午10:37
 */

class SceReportController extends BaseController
{
    /*
     * 未收明细
     * */
    public function order_non_receivable_detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date' => 'required',
                'shop' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop = Input::get('shop');
            $date = Input::get('date');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            $orders = Orders::whereIn('status',array(1216,1416))
                ->whereBetween('created_at',array($date.' 00:00:00',$date.' 23:59:59'))
                ->where('shop_id',$shop)
                ->where('place',2)
                ->select(array('order_id','car_no','name','amount','payable_amount'))
                ->get()
                ->toArray();
            $result = array(
                'data' => $orders
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce", "event" => "order_non_receivable_detail", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /*
     * 应收明细
     * */
    public function order_receivable_detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date' => 'required',
                'shop' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop = Input::get('shop');
            $date = Input::get('date');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            $orders = Orders::whereIn('status',array(1018,1017,1217,1317,1417))
                ->whereBetween('pay_time',array($date.' 00:00:00',$date.' 23:59:59'))
                ->where('shop_id',$shop)
                ->where('place',2)
                ->where('pay_type',6)
                ->select(array('order_id','car_no','name','amount','payable_amount'))
                ->get()
                ->toArray();
            $result = array(
                'data' => $orders
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce", "event" => "order_receivable_detail", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /*
     * 技师绩效
     * */
    public function engineer_work_total()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date' => 'required',
                'shop' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop = Input::get('shop');
            $date = Input::get('date');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            $engineer_work_detail = Report::get_engineer_work_detail($date.' 00:00:00',$date.' 23:59:59',$shop);
            $enginers=array();
            if(!empty($engineer_work_detail)){
                foreach ($engineer_work_detail as $_r) {
                    if(isset($enginers[$_r['order_engineer_id']])){
                        if(!in_array($_r['order_id'],$enginers[$_r['order_engineer_id']]["order_arr"])){
                            $enginers[$_r['order_engineer_id']]["order_arr"][]=$_r['order_id'];
                            $enginers[$_r['order_engineer_id']]["car_total"]+=1;
                            $enginers[$_r['order_engineer_id']]["car_check_total"]+=1;
                        }
                    }else{
                        $enginers[$_r['order_engineer_id']]=array(
                            "name"=>$_r['order_engineer'],
                            "sale_amount"=>0,
                            "car_total"=>1,
                            "car_check_total"=>1,
                            "order_arr"=>array($_r['order_id']),
                            "product"=>array(),
                        );
                    }
                    if(isset($enginers[$_r['product_engineer_id']])){
                        $enginers[$_r['product_engineer_id']]["sale_amount"]+=($_r['counter_amount']);
                        $exist = 0;
                        foreach ($enginers[$_r['product_engineer_id']]["product"] as &$_tmp_product){
                            if($_tmp_product['id'] == $_r['level_3_id']){
                                $_tmp_product['num']+=1;
                                $exist = 1;
                                break;
                            }
                        }
                        if($exist == 0){
                            $_product = array(
                                'id'=>$_r['level_3_id'],
                                'name'=>$_r['level_3_name'],
                                'num'=>1
                            );
                            array_push($enginers[$_r['product_engineer_id']]["product"],$_product);
                        }
                    }else{
                        $enginers[$_r['product_engineer_id']]=array(
                            "name"=>$_r['product_engineer'],
                            "sale_amount"=>$_r['counter_amount'],
                            "car_total"=>0,
                            "car_check_total"=>0,
                            "order_arr"=>array(),
                            "product"=>array(
                                array(
                                    'id'=>$_r['level_3_id'],
                                    'name'=>$_r['level_3_name'],
                                    'num'=>1
                                )
                            ),
                        );
                    }
//                    if(!isset($work_total[$_r['level_3_id']])){
//                        $work_total[$_r['level_3_id']]=array(
//                            'level_1_id'=>$_r['level_1_id'],
//                            'level_1_name'=>$_r['level_1_name'],
//                            'level_2_id'=>$_r['level_2_id'],
//                            'level_2_name'=>$_r['level_2_name'],
//                            'level_3_id'=>$_r['level_3_id'],
//                            'level_3_name'=>$_r['level_3_name'],
//                        );
//                    }
                }
            }


//            foreach ($enginers as $_enginers){
//                var_dump($_enginers['product']);
//                foreach ($_enginers['product'] as $product => $num){
//                    var_dump($product);
//                    var_dump($num);
//                }
//                exit;
//            }
//            exit;
            $data = array();
            foreach ($enginers as $_enginers){
                array_push($data,$_enginers);
            }

            $result = array(
                'data' => $data
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce", "event" => "engineer_work_total", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /*
     * 技师绩效
     * */
    public function engineer_work_total_time()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                break;
            }
            $this_month_start = date("Y-m-01 00:00:00");
            $this_month_end = date("Y-m-d H:i:s",strtotime($this_month_start)+ date("t")*60*60*24-1);
            $enginers_this_month = $this->engineer_work($this_month_start,$this_month_end,$engineer_data);
            
            $timestamp = strtotime(date("Y-m"));
            $front_month_start = date('Y-m-01 00:00:00',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));
            $front_month_end = date("Y-m-d H:i:s",strtotime($front_month_start)+ date("t",  strtotime($front_month_start))*60*60*24-1);
            $enginers_front_month = $this->engineer_work($front_month_start,$front_month_end,$engineer_data);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => ["this_month"=>$enginers_this_month, "front_month"=>$enginers_front_month]);
        } while (false);
        Log::info("info", array("system" => "sce", "event" => "engineer_work_total", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }
    
    public function engineer_work($start,$end,$engineer_data){
        $enginers = [247=>['name'=>'更换机油机滤','count'=>0,'id'=>247],253=>['name'=>'更换变速箱油(自动).','count'=>0,'id'=>253],257=>['name'=>'更换转向助力油.','count'=>0,'id'=>257],
            836=>['name'=>'更换制动液','count'=>0,'id'=>836],252=>['name'=>'更换变速箱油(手动).','count'=>0,'id'=>252],262=>['name'=>'更换防冻液(冷却液).','count'=>0,'id'=>262],
            1510=>['name'=>'燃油系统清洗','count'=>0,'id'=>1510],267=>['name'=>'清洗进气道(免拆).','count'=>0,'id'=>267],254=>['name'=>'更换/拆装火花塞.','count'=>0,'id'=>254],
            272=>['name'=>'四轮定位.','count'=>0,'id'=>272],258=>['name'=>'更换/拆装刹车片(前).','count'=>0,'id'=>258],259=>['name'=>'更换/拆装刹车片(后).','count'=>0,'id'=>259],
            1512=>['name'=>'更换蓄电池.','count'=>0,'id'=>1512],1517=>['name'=>'更换轮胎.','count'=>0,'id'=>1517]];
        $enginers_keys = array_keys($enginers);
        $car_total = 0;
        $car_check_total = 0;
        $order_ids = [];
        $engineer_work_detail = Report::get_engineer_work_detail($start,$end,$engineer_data->type_id);
        if(!empty($engineer_work_detail)){
            foreach ($engineer_work_detail as $_r) {
                if($_r['reteurn_type']==0){//不是退货记录才记录
                    if ($engineer_data->id == $_r['order_engineer_id']) { //过滤出当前用户下的数据
                        if (in_array($_r['level_3_id'], $enginers_keys)) {
                            $enginers[$_r['level_3_id']]['count'] +=1;
                        }
                        if (!in_array($_r['order_id'],$order_ids)) {
                            $car_total += 1;
                            $car_check_total +=1;
                            $order_ids[] = $_r['order_id'];
                        }
                    }
                }
            }
        }
        $array = ['car_total'=>$car_total,'car_check_total'=>$car_check_total,"enginers"=>array_values($enginers)];
        return $array;
    }
    
    
    /*
     * 流水详情
     * */
    public function detail_order_data()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date' => 'required',
                'shop' => 'required',
                'type' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        $orders = array();
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop = Input::get('shop');
            $date = Input::get('date');
            $type = Input::get('type');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            $order_profits = Report::get_profit_report($date.' 00:00:00',$date.' 23:59:59',$shop);
            foreach ($order_profits as $_order_profit){
                if($_order_profit['order_type'] == $type){
                    $order = array(
                        'order_id' => $_order_profit['order_id'],
                        'car_no' => $_order_profit['car_no'],
                        'user' => $_order_profit['name'],
                        'amount' => $_order_profit['order_amount'],
                        'profit' => $_order_profit['profit'],
                    );
                    array_push($orders,$order);
                }
            }
            $result = array(
                'data' => $orders
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce", "event" => "detail_order_data", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /*
     * 流水数据
     * */
    public function total_order_data()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date' => 'required',
                'shop' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop = Input::get('shop');
            $date = Input::get('date');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            //余额
            $balance = DB::select('select sum(payable_amount) as amount from orders where pay_type = 8 and status in (1018,1017,1217,1317,1417) and shop_id = ? and date(pay_time) = ?', array($shop,$date));
            //挂账
            $credit =  DB::select('select sum(payable_amount) as amount from orders where pay_type = 6 and status in (1018,1017,1217,1317,1417) and shop_id = ? and date(pay_time) = ?', array($shop,$date));
            //现金
            $cash = DB::select('select sum(payable_amount) as amount from orders where pay_type = 1 and status in (1018,1017,1217,1317,1417) and shop_id = ? and date(pay_time) = ?', array($shop,$date));
            //刷卡
            $pos = DB::select('select sum(payable_amount) as amount from orders where pay_type = 7 and status in (1018,1017,1217,1317,1417) and shop_id = ? and date(pay_time) = ?', array($shop,$date));

            $service_order_amount = 0;
            $service_order_profit = 0;
            $sale_order_amount = 0;
            $sale_order_profit = 0;
            $order_profits = Report::get_profit_report($date.' 00:00:00',$date.' 23:59:59',$shop);
            foreach ($order_profits as $_order_profit){
                if($_order_profit['order_type'] == 1){
                    $service_order_amount = $service_order_amount + (int) $_order_profit['order_amount'];
                    $service_order_profit = $service_order_profit + (int) $_order_profit['profit'];
                }elseif($_order_profit['order_type'] == 2){
                    $sale_order_amount = $sale_order_amount + (int) $_order_profit['order_amount'];
                    $sale_order_profit = $sale_order_profit + (int) $_order_profit['profit'];
                }
            }
            $result = array(
                'data' => array(
                    'balance' => (int)$balance[0]->amount,
                    'credit' => (int)$credit[0]->amount,
                    'cash' => (int)$cash[0]->amount,
                    'pos' => (int)$pos[0]->amount,
                    'service_order_amount' => $service_order_amount,
                    'service_order_profit' => $service_order_profit,
                    'sale_order_amount' => $sale_order_amount,
                    'sale_order_profit' => $sale_order_profit
                )
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce", "event" => "total_order_data", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /*
     * 经营数据
     * */
    public function total_operating_data()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'date' => 'required',
                'shop' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("sce_error.login_args_error_1001");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop = Input::get('shop');
            $date = Input::get('date');

            //验证token
            $engineer_data = MaintenanceEngineers::getEngineerByToken($token,$response);
            if(is_null($engineer_data)){
                
                break;
            }

            $data = ReportOperatingData::where('shop',$shop)
                    ->where('date',$date)
                    ->get()
                    ->toArray();

            $result = array(
                'data' => $data,
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "sce", "event" => "total_operating_data", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }
}